#include "XpmDocTranslator.h"

namespace xpm {

	void XpmDocTranslator::translateAll(const wstring& syntax,   const XpmTermDoc& doc, wstring& _syntax, XpmTermDoc& _doc) {
		if (_termFactory != 0) {
			string lang = otherLang( doc.lang());
			cout << "translate to :" << lang << endl;
			_termControl = _termFactory->termControl(lang);
			wcout << "from: " << syntax << endl;
			
			//copy syntax to output
			_syntax = syntax;
			//copy doc to _doc
			_doc = doc;
			//chang the lang to the other



			_doc.setLang(lang);
			TermBlocks blocks = _doc.GetTermBlocks();
			// reverse process
			for(TermBlocks::reverse_iterator it = blocks.rbegin(); it != blocks.rend(); ++it) {
				int bp = (*it)->position();
				for(list<TermRange>::reverse_iterator tit = (*it)->GetTerms().rbegin(); tit != (*it)->GetTerms().rend(); ++tit) {
					int pos = bp + tit->posInBlock();
					wstring signifier = tit->text();  // utf-16
					string iid = tit->iid();
					int len = signifier.length();
					conex::Term* term = _termControl->GetTermByIid(iid);
					if ( term != 0 ) {
						// begin to translate singe term
						wstring _text = _termControl->TopWord( term);
						wcout << "_text:" << _text << endl;
						int _len = _text.length();
						// replace the text
						_syntax.replace(pos, len, _text);
						
						/*TermRange range = *tit;
						range.setText(L"11");
						range.setTerm(term);*/
						// replace termrange
						tit->setText(_text);						
						// iid is the same in general, it is not needed to modify
						// but the term needs change from one lang to anthoer
						tit->setTerm(term);
						// process Add chars or Remove chars
						cout << "length of tern range :" << tit->length() << endl;
						int delt = _len - len;
						int startpos = delt < 0 ? pos + _len : pos + len;
						if ( delt > 0 ) {
							(*it)->AddSomethingBefore(startpos, delt);
							_doc.AddSomethingBefore(startpos, delt);
						}else if ( delt < 0 ) {
							(*it)->RemoveSomethingBefore(startpos, -delt);
							_doc.RemoveSomethingBefore(startpos, -delt);
						}	
						cout << "length of tern range :" << tit->length() << endl;
						wcout << "text of term range :" << tit->text() << endl;
					}
				}
			}
			wcout << "to: " << _syntax << endl;
		}
	}

	void XpmDocTranslator::translateNames(wstring syntax, XpmTermDoc doc, wstring& _syntax, XpmTermDoc& _doc) {

	}
}